package backend

import (
	"blog/service/page"
	"net/http"
	"strconv"
	"time"

	"gitee.com/xchengli/blog-lib/common"
	"gitee.com/xchengli/blog-lib/session"

	"github.com/gin-gonic/gin"
)

/*
*
 */
func AdminPostsListHandle(ctx *gin.Context) {
	guest := new(session.GuestSession)
	//检查是否未登录
	if guest.Init(ctx.Request).CheckIsLogin() == false {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
		return
	}

	//页号
	pageId, err := strconv.ParseInt(ctx.Query("page"), 10, 64)
	if err != nil {
		pageId = 1
	}
	if pageId < 1 {
		pageId = 1
	}
	//每一页数据条数
	PageSize, _ := strconv.ParseInt(ctx.Query("pageSize"), 10, 64)
	if PageSize == 0 {
		PageSize = int64(20)
	}

	//关键字
	keyWord := func() string {
		param1 := ctx.Param("keyWord")
		if param1 != "" {
			return param1
		}
		param2 := ctx.Query("keyWord")
		return param2
	}()
	//分类
	typeId := func() int64 {
		param1, _ := strconv.ParseInt(ctx.Param("type"), 10, 64)
		if param1 != 0 {
			return param1
		}
		param2, _ := strconv.ParseInt(ctx.Query("type"), 10, 64)
		return param2
	}()
	//标签
	tagName := func() string {
		param1 := ctx.Param("tagName")
		if param1 != "" {
			return param1
		}
		param2 := ctx.Query("tagName")
		return param2
	}()

	// 使用PS层服务
	adminPostService := page.NewAdminPostPageService()
	lists := adminPostService.GetPostListByKeyword(ctx, keyWord, tagName, typeId, pageId, PageSize)
	ctx.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": lists})
}

/**
 * @api            		{POST} /admin/posts/add 文章添加
 * @apiName        		admin posts add
 * @apiGroup       		admin/posts
 * @apiVersion     		1.0.0
 * @apiDescription 		文章添加
 * @apiPermission  		admin
 * @apiSampleRequest 	/admin/posts/add
 * @apiParam {number} 	post_type     分类id
 * @apiParam {string} 	title         标题
 * @apiParam {string} 	content       内容
 * @apiParam {number} 	is_private    是否私有 1是0否
 * @apiParam {number} 	is_show       是否显示 1是0否
 * @apiParam {number} 	is_remark     是否允许评论 1是0否
 * @apiParam {number} 	is_temp       是否草稿 1是0否
 * @apiParam {number} 	is_star       是否标星 1是0否
 * @apiParam {number} 	add_time      添加时间(可选 2018-09-04 16:29:34)
 */
func AdminPostsAddHandle(ctx *gin.Context) {
	guest := new(session.GuestSession)
	//检查是否未登录
	if guest.Init(ctx.Request).CheckIsLogin() == false {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
		return
	}

	// 使用PS层服务
	adminPostService := page.NewAdminPostPageService()

	// 使用 ps 层创建数据结构
	post := adminPostService.CreatePostDataReal()
	post.Author = int(guest.UID)

	postType, _ := strconv.ParseInt(ctx.PostForm("post_type"), 10, 64)
	is_postType_ok := adminPostService.ValidatePostType(ctx, postType)
	if is_postType_ok == false {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "分类ID错误"})
		return
	}
	post.PostType = int(postType)

	title := common.TrimHtml(ctx.PostForm("title"))
	is_title_ok, errMsg := adminPostService.ValidatePostTitle(title)
	if is_title_ok == false {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": errMsg})
		return
	}
	post.Title = title

	content := ctx.PostForm("content")
	is_content_ok, errMsg := adminPostService.ValidatePostContent(content)
	if is_content_ok == false {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": errMsg})
		return
	}
	post.Content = content

	if ctx.PostForm("is_private") == "1" {
		post.IsPrivate = 1
	} else {
		post.IsPrivate = 0
	}

	if ctx.PostForm("is_show") == "0" {
		post.IsShow = 0
	} else {
		post.IsShow = 1
	}

	if ctx.PostForm("is_remark") == "0" {
		post.IsRemark = 0
	} else {
		post.IsRemark = 1
	}

	if ctx.PostForm("is_temp") == "1" {
		post.IsTemp = 1
	} else {
		post.IsTemp = 0
	}

	if ctx.PostForm("is_star") == "1" {
		post.IsStar = 1
	} else {
		post.IsStar = 0
	}

	param_addTime := ctx.PostForm("add_time")
	if param_addTime != "" {
		T, err := adminPostService.ParseTimeLayout(param_addTime)
		if err != nil {
			post.CreateTime = adminPostService.FormatTimeLayout(time.Now())
		}
		post.CreateTime = adminPostService.FormatTimeLayout(T)
	} else {
		post.CreateTime = adminPostService.FormatTimeLayout(time.Now())
	}
	post.LastEditTime = post.CreateTime

	err := adminPostService.CreatePost(ctx, post)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "保存失败"})
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": post.ID})
		// TODO: Add Elasticsearch indexing when available
	}
}

/**
 * @api            		{POST} /admin/posts/update 文章编辑
 * @apiName        		admin posts update
 * @apiGroup       		admin/posts
 * @apiVersion     		1.0.0
 * @apiDescription 		文章编辑
 * @apiPermission  		admin
 * @apiSampleRequest 	/admin/posts/update
 * @apiParam {number} 	post_type     分类id
 * @apiParam {string} 	title         标题
 * @apiParam {string} 	content       内容
 * @apiParam {number} 	is_private    是否私有 1是0否
 * @apiParam {number} 	is_show       是否显示 1是0否
 * @apiParam {number} 	is_remark     是否允许评论 1是0否
 * @apiParam {number} 	is_temp       是否草稿 1是0否
 * @apiParam {number} 	is_star       是否标星 1是0否
 */
func AdminPostsUpdateHandle(ctx *gin.Context) {
	guest := new(session.GuestSession)
	//检查是否未登录
	if guest.Init(ctx.Request).CheckIsLogin() == false {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
		return
	}

	// 使用PS层服务
	adminPostService := page.NewAdminPostPageService()

	id, err := strconv.ParseInt(ctx.PostForm("id"), 10, 64)
	if err != nil || id == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "文章ID错误"})
		return
	}

	post, err := adminPostService.GetPostByID(ctx, id)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "文章未找到"})
		return
	}

	postType, _ := strconv.ParseInt(ctx.PostForm("post_type"), 10, 64)
	is_postType_ok := adminPostService.ValidatePostType(ctx, postType)
	if is_postType_ok == false {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "分类ID错误"})
		return
	}
	post.PostType = int(postType)

	title := common.TrimHtml(ctx.PostForm("title"))
	is_title_ok, errMsg := adminPostService.ValidatePostTitle(title)
	if is_title_ok == false {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": errMsg})
		return
	}
	post.Title = title

	content := ctx.PostForm("content")
	is_content_ok, errMsg := adminPostService.ValidatePostContent(content)
	if is_content_ok == false {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": errMsg})
		return
	}
	post.Content = content

	if ctx.PostForm("is_private") == "1" {
		post.IsPrivate = 1
	} else {
		post.IsPrivate = 0
	}

	if ctx.PostForm("is_show") == "0" {
		post.IsShow = 0
	} else {
		post.IsShow = 1
	}

	if ctx.PostForm("is_remark") == "0" {
		post.IsRemark = 0
	} else {
		post.IsRemark = 1
	}

	if ctx.PostForm("is_temp") == "1" {
		post.IsTemp = 1
	} else {
		post.IsTemp = 0
	}

	if ctx.PostForm("is_star") == "1" {
		post.IsStar = 1
	} else {
		post.IsStar = 0
	}

	post.LastEditTime = adminPostService.FormatTimeLayout(time.Now())

	err = adminPostService.UpdatePost(ctx, post)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败"})
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 0, "message": "success", "data": post.ID})
	}
}
